// wGPS.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <Windows.h>
#include "CSensorEvents.h"
#include "CSensorManagerEvents.h"
#include <Sensorsapi.h>
#include <sensors.h>
#include <SensAPI.h>
#include <initguid.h>
#include <propkeydef.h>
#include <comutil.h>
#include <math.h>

#pragma comment(lib, "Sensorsapi.lib")

CSensorManagerEvents* m_pSensorManagerEvents;
#define DEBUG 1

bool EnableSensor()
{
	ISensorManager *pSensorManager;
	ISensorCollection *pSensorColl;
	ISensor *pSensor;
	ULONG uCount;
	HRESULT hr= S_OK;
	HWND hWnd=GetConsoleWindow(); 

	hr = CoCreateInstance(CLSID_SensorManager,NULL,
							CLSCTX_INPROC_SERVER,
							IID_PPV_ARGS(&pSensorManager));
	if (FAILED(hr))
	{
		printf("\n[-] CoCreateInstance() fail!");
		return 0;
	}

	hr = pSensorManager->GetSensorsByType(SENSOR_TYPE_LOCATION_GPS, &pSensorColl);
	if (FAILED(hr))
	{
		printf("\n[-] GetSensorsByCategory() fail!");
		printf("\n[-] No any sensors were found!");
		return 0;
	}

	printf("Now enable GPS sensors...\n");

	if (SUCCEEDED(pSensorManager->RequestPermissions(hWnd, pSensorColl, 0))){
#if DEBUG
			printf("User enabled GPS location\n");
#endif
	}else{
			printf("User disabled GPS location\n");
			return false;
	}

	hr = pSensorColl->GetCount(&uCount);
	if (FAILED(hr))
	{
		printf("\n[-] GetCount fail, ");
		return 0;
	}

	for (ULONG i=0; i<uCount; i++)
	{
		if(SUCCEEDED(pSensorColl->GetAt(i, &pSensor)))
		{
			BSTR fName;
			pSensor->GetFriendlyName(&fName);
			printf("[I] %S\n", fName);
			SysFreeString(fName);
		}
	}
		return uCount;
}

int getSensors(int sType)
{
	m_pSensorManagerEvents = new CSensorManagerEvents();
	if (SUCCEEDED(m_pSensorManagerEvents->Initialize()))
		return 0;
	else
		return 1;
}

int _tmain(int argc, _TCHAR* argv[])
{
	MSG msg;

	CoInitialize(0); 
  
	if(EnableSensor() == false) 
		exit(1);

	getSensors(0);

	while (GetMessage(&msg, NULL, 0, 0))
	{ 
		if (!TranslateAccelerator(msg.hwnd, NULL, &msg))  
		{  
			TranslateMessage(&msg);  
			DispatchMessage(&msg);  
		} 
	}
	CoUninitialize();
	return 0;
}

